function navTo(e){
  var url = e.currentTarget.dataset.url
  var val = e.currentTarget.dataset.val
  var id = e.currentTarget.dataset.id
  if(val){
    wx.navigateTo({
      url: url +'?id=' + id,
    })
  }else{
    wx.navigateTo({
      url: url,
    })
  }
}

function navToTab(e){
  var url = e.currentTarget.dataset.url
  wx.switchTab({
    url: url,
  })
}

function onInput(event,that) {
  if(event.currentTarget.dataset.key){
    var key = event.currentTarget.dataset.key
    that.setData({
      [key]: event.detail,
    });
  }
}

function onClick(event,that){
  var key = event.currentTarget.dataset.key
  var val = event.currentTarget.dataset.val
  if(key){
    that.setData({
      [key]:val
    })
  }
}
// 1.成功 2.错误 3.加载
function showText(event,type){
  if(event){
    if(type == 1){
      wx.showToast({
        title:event,
        icon:'success'
      })
    }else if(type == 2){
      wx.showToast({
        title:event,
        icon:'error'
      })
    }else if(type == 3){
      wx.showToast({
        title: event,
        icon:'loading'
      })
    }
  }
}

// 添加商品
function addCardList(goods){
  // goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state
  if(JSON.stringify(goods) !== "{}"){
      var list = wx.getStorageSync('cart') || []
      if(list.length <= 50){
        var findResult = list.find((x)=>x.goods_id == goods.goods_id)
        if(!findResult){
          var obj = {
            goods_id:goods.goods_id,
            goods_name:goods.goods_name,
            goods_price:goods.goods_price,
            goods_count:goods.goods_count,
            goods_small_logo:goods.goods_small_logo,
            goods_state:goods.goods_state
          }
          list.push(obj)
          wx.setStorageSync('cart', list)
          showText('加入成功！',1)
          return 1
        }else{
          showText('购物车已有该商品！',1)
          return 2
        }
      }else{
        showText('购物车已满!',2)
      }
  }
}
// 总数量
// 统计购物车中商品的总数量
function total() {
  var num = 0
  var list = wx.getStorageSync('cart')
  list.forEach(item => {
    num += item.goods_count
  });
  wx.setStorageSync('total', num || 0)
}



module.exports = {
  navTo,
  navToTab,
  onInput,
  onClick,
  showText,
  addCardList,
  total
}